package com.jmex.physics.impl.jbullet.replacementShape;

import javax.vecmath.Matrix3f;
import javax.vecmath.Vector3f;

import com.bulletphysics.collision.shapes.CylinderShapeZ;
import com.bulletphysics.linearmath.MatrixUtil;
import com.bulletphysics.linearmath.Transform;

/**
 * 
 * This CylinderShape semi-hack addresses two problems.  First, the JBullet
 * default cylinder is formed around the Y axis, rather than Z.  Secondly,
 * the AABB formula built into the default CylinderShape is wrong.  I've
 * gone ahead and grabbed the original implementation (mysteriously commented
 * out) from BoxShape and pasted it in here.  It works well enough for now.
 * 
 * The alternative is late-detected collisions which obviously will rebound
 * very, very oddly.
 * 
 * @author Falken224
 *
 */
public class JMECompatibleCylinderShape extends CylinderShapeZ {

	public JMECompatibleCylinderShape(Vector3f halfExtents) {
		super(halfExtents);
	}

	@Override
	public void getAabb(Transform t, Vector3f aabbMin, Vector3f aabbMax) {
		//Copied from BoxShape.  The current implementation set up for _PolyhedralConvexShape in the
		//CylinderShape superclass doesn't do bounding correctly.
		stack.pushCommonMath();
		try {
			Vector3f halfExtents = getHalfExtentsWithoutMargin();

			Matrix3f abs_b = stack.matrices.get(t.basis);
			MatrixUtil.absolute(abs_b);

			Vector3f tmp = stack.vectors.get();

			Vector3f center = stack.vectors.get(t.origin);
			Vector3f extent = stack.vectors.get();
			abs_b.getRow(0, tmp);
			extent.x = tmp.dot(halfExtents);
			abs_b.getRow(1, tmp);
			extent.y = tmp.dot(halfExtents);
			abs_b.getRow(2, tmp);
			extent.z = tmp.dot(halfExtents);

			extent.add(stack.vectors.get(getMargin(), getMargin(), getMargin()));

			aabbMin.sub(center, extent);
			aabbMax.add(center, extent);
		}
		finally {
			stack.popCommonMath();
		}
	}	
}
